package com.zerocarbon.framework.web.utils;

import com.zerocarbon.framework.core.extension.IAppSecretUtil;
import com.zerocarbon.framework.core.model.AppInfo;
import com.zerocarbon.framework.web.properties.RestProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * APP应用管理工具类。在init方法及配置文件拿到AppKey及AppSecret信息塞到本地Map缓存。
 * 获取AppInfo时，若缓存不存在，使用IAppResolverHandler通过Feign从远程数据库读取
 * @author wyf
 */
@Slf4j
public class AppSecretUtil implements IAppSecretUtil {
	
	@Autowired
	private RestProperties restProperties;
	
	/*@Autowired
	private IAppResolverHandler iAppResolverHandler;*/
    
	/**
	 * App应用信息管理缓存， 缓存来源三个地方，1、本地init方法中添加（不允许其他人添加）
	 * 									    2、从restProperties配置文件中添加（建议只添加PC的appkey和secret） 
	 *                                      3、通过IAppResolverHandler获取，该方式来于feign调用(AppResolveApi),或业务工程本地实现IAppResolverHandler接口
	 */
    private static Map<String, AppInfo> APP_SECRET_MAP = new ConcurrentHashMap<String, AppInfo>();        //应用关系  appKey-appInfo
    
    @PostConstruct
    public void init() {
    	// 从配置文件读取
    	if(restProperties.getAppSecretMap() != null) {
    		restProperties.getAppSecretMap().forEach((k, v) -> this.addAppSecretMap(this.createAppInfo(k, v, null)));
    	}
    }
    
    private AppInfo createAppInfo(String appKey, String appSecret, Long tenantId) {
    	return AppInfo.builder().appKey(appKey).appSecret(appSecret).tenantId(tenantId).build();
    }

    /**
     * 添加缓存
     */
    @Override
    public void addAppSecretMap(AppInfo appInfo) {
    	APP_SECRET_MAP.put(appInfo.getAppKey(), appInfo);
    }
    
    /**
     * 根据appKey 获取AppInfo，先从本地缓存读取，在从AppResolverHandler读取
     */
    @Override
    public AppInfo getAppInfoByAppKey(String appKey) {
        if (appKey == null || "".equals(appKey)) return null;
        AppInfo appInfo = APP_SECRET_MAP.get(appKey);
        if(appInfo == null) { //不存在，通过AppResolverHandler获取
        	/*Result<AppInfo> result = iAppResolverHandler.getAppInfoByKey(appKey);
        	if (!result.getIsSuccess()) {
        	    throw new BusinessException(result.getCode(), result.getMessage());
            }
        	log.info("[getAppInfoByAppKey] param.appKey="+ result +" result=" + JSON.toJSONString(result));
        	if(result!=null && result.getData()!=null) {
        		appInfo = result.getData();
        		this.addAppSecretMap(appInfo);
        	}*/
        }
        return appInfo;
    }

    /**
     * 根据appKey 获取app_secret，先从本地缓存读取，在从AppResolverHandler读取
     */
    @Override
    public String getAppSecretByAppKey(String appKey) {
        if (appKey == null || "".equals(appKey)) return null;
        AppInfo appInfo = this.getAppInfoByAppKey(appKey);
        if(appInfo!=null)
        	return appInfo.getAppSecret();
        return null;
    }

    /**
     * 根据appKey 获取tenantId，先从本地缓存读取，在从AppResolverHandler读取
     */
    @Override
    public Long getTenantIdByAppKey(String appKey) {
        if (appKey == null || "".equals(appKey)) return null;
        AppInfo appInfo = this.getAppInfoByAppKey(appKey);
        if(appInfo!=null)
        	return appInfo.getTenantId();
        return null;
    }
}
